<?php

class Controller extends CController {

    public $breadcrumbs = array();
    public $menu = array();
    public $keyWord = 'hyho';
    public $description = 'hyho';
    public $statistic;

    public function init() {
        $route = Yii::app()->urlManager->parseUrl(Yii::app()->getRequest());
        if(Y::isAuthed() && $route != 'user/logout') {
            $user = User::model()->findByPk(Y::userId());
            if($route != "user/setemail" && $user) {
                $ne = substr(md5($user->service_name . $user->identity), 0, 12);
                if($user->email == $ne . "@example.com") {
                    $this->redirect("/user/set/email");
                }
            }
            if($user) {
                $user->lastvisit = time();
                $user->save(false);
            }
        }
        return parent::init();
    }

    public function loadUser($id) {
        $user = User::model()->findByPk($id);
        if(!$user) throw new CHttpException(404);
        return $user;
    }

    public function loadService($id) {
        $service = Service::model()->findByPk($id);
        if(!$service) throw new CHttpException(404);
        return $service;
    }

    public function loadSuggest($id) {
        $suggest = Suggest::model()->findByPk($id);
        if(!$suggest) throw new CHttpException(404);
        return $suggest;
    }

    public function loadUserByName($name) {
        $user = User::model()->find("LOWER(username) = :username", array(":username" => strtolower($name)));
        if(!$user) throw new CHttpException(404);
        return $user;
    }

    public function sendMail($to, $template, $params, $subject) {
        $email = Yii::app()->email;
        $email->to = $to;
        $email->from = Y::param('emailFrom') . " <" . Y::param('adminEmail') . ">";
        $email->message = Yii::app()->controller->renderPartial($template, $params, true);
        $email->subject = $subject;
        $email->send();
    }
}
